import fs from "fs";
import path from "path";
import express from "express";
import bodyParser from "body-parser";
import uuid from "node-uuid";
import {userApprove,dbConnTest,userRegister,userLogin,userUpdate,userLogins,bookSellRelease,management} from "./mySqlHandler";
import {imgBuilderArr2 } from "./fileBuilder";
const filePath =path.join(__dirname,'./public')
const gloabl = {
    port: 3205,
    publicPath: path.join(__dirname, "public"),
    dataPath: path.join(__dirname, "data"),
}
const app = express();

const appConfig = () => {
    app.use(bodyParser.json({ limit: '50mb' }));
    app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
    app.use(express.json({ limit: '50mb' }));
    app.use(express.urlencoded({ limit: '50mb' }));
    app.use(express.static(gloabl.publicPath));
}
appConfig();

// qrDecode(gloabl.dataPath +"/22.jpg",res=>{
//     console.log(res);
// })

app.listen(gloabl.port, () => {
    console.log("---> data-server-running");
    console.log("http://localhost:" + gloabl.port);
});

// 管理员登录
app.post("/loginAdmin", (request, response) => {
    let loginUser = request.body;
    let msgBody = {
        code: "01",
        msg: "验证通过",
        data: null
    };

    if (!fs.existsSync(path.join(gloabl.dataPath, "userInfoAdmin.json"))) {
        msgBody = {
            code: "404",
            msg: "管理员数据连接失败",
            data: null
        };
        return response.send(msgBody);
    }

    let users = JSON.parse(fs.readFileSync(path.join(gloabl.dataPath, "userInfoAdmin.json"), "utf-8"));
    let target = users.find(item => item.username === loginUser.username);

    if (!target) {
        msgBody = {
            code: "02",
            msg: "管理员不存在",
            data: null
        }
    } else {
        if (target.password !== loginUser.password) {
            msgBody = {
                code: "03",
                msg: "密码错误",
                data: null
            }
        } else {
            delete target.pass;
            msgBody.data = target;
        }
    }
    response.send(msgBody);
});

/*----------------以上为管理员接口------------------*/

// 数据库连接测试
app.get("/dbconntest", (request, response) => {
    dbConnTest(res => {
        if (res.code == "01") {
            response.send({ code: "01", msg: "ok", data: res.data });
        } else {
            console.log(res);
            response.send({ code: "04", msg: "error", data: res });
        }
    });
})

/*---获取验证码---*/
app.get("/getVerfityCode", (request, response) => {
    let query = request.query;
    console.log("query->>>", query);
    let vercode = "";
    for (let i = 0; i < 4; i++) {
        vercode += Math.floor(Math.random() * 10);
    }
    response.send({ code: "01", msg: "test", data: vercode });
});

// 用户注册
app.post("/register", (request, response) => {
    console.log(request.body);
    let { nickname, password, phonenum } = request.body
    userRegister(uuid.v1(), nickname, password, phonenum, res => {
        if (res.code == "01") {
            response.send({ code: "01", msg: "ok", data: res.data });
        }else{
            response.send({ code: "03", msg: "error", data:null });
        } 
    })
})
//用户登录
app.get("/login", (request, response) => {
    let { password, phonenum } = request.query
    userLogin(phonenum, password, res => {
        if (res.code === "01") {
            console.log(res);
            if (res.data.length >= 1) {
                response.send({ code: "01", msg: "ok", data: res.data[0] });
            } else {
                response.send({ code: "02", msg: "ok", data: null });
            }

        } else {
            response.send({ code: "04", msg: "error", data: null });
        }
    })
})

//用户登录  验证码登录
app.get("/logins",(request,response)=>{
    console.log(request.query);
    let {phonenum} = request.query
    userLogins(phonenum,res=>{
        if(res.code==="01"){
            if(res.data.length>=1){
                response.send({ code: "01", msg: "ok", data: res.data[0]});
            }else{
                response.send({ code: "02", msg: "ok", data:null});
            }
           
        }else{
            response.send({ code: "04", msg: "error", data:null });
        }
    })
})

//学生信息认证
app.post("/approve",(request,response)=>{
    console.log(request.body);
    let {realname,collage,uid,sex} =request.body
    userApprove(realname,collage,uid,sex,res=>{
        if(res.code==="01"){
            response.send({code:"01", msg:"ok",data:null})
        }else{
            response.send({code:"04",msg:"err",data:null})
        }
    })
})

//用户信息的修改
app.post("/update", (request, response) => {
    let { nickname, phonenum, uid, email, age, head_url, signature } = request.body
        // 相当于加唯一标识符
    let head_filename = Date.now() + '.png';
    //存储图片的路径
    const imgPath = path.join(filePath, "/image/usersHead/") + head_filename;
    //去掉图片base64码前面部分data:image/png;base64
    const base64 = head_url.replace(/^data:image\/\w+;base64,/, "");
    //把base64码转成buffer对象，
    const dataBuffer = new Buffer(base64, 'base64');
    //文件的写入
    var head_urls = "/image/usersHead/" + head_filename
    fs.writeFile(imgPath, dataBuffer, function(err) {
        if (err) {} else {
            console.log('写入成功！');
        }
    });
    userUpdate(nickname, phonenum, uid, email, age, head_urls, signature, res => {
        if (res.code === "01") {
            response.send({ code: "01", msg: "ok", data: head_urls })
        } else {
            response.send({ code: "04", msg: "err", data: null })
        }
    })
})



// 图书发布
app.post("/bookSellRelease", (req, response) => {
    let bookinfo = req.body;
    let {
        cover: coverSrc,
        legend_1: legend_1Src,
        legend_2: legend_2Src,
        legend_3: legend_3Src,
    } = bookinfo;

    

    imgBuilderArr2([coverSrc,legend_1Src,legend_2Src,legend_3Src],"bookImgs", res => {
        bookinfo.cover = res[0];
        bookinfo.legend_1 = res[0];
        bookinfo.legend_2 = res[0];
        bookinfo.legend_3 = res[0];
        bookinfo.bid=uuid.v1();
        console.log("resList",bookinfo);
        bookSellRelease(bookinfo,result=>{
            if (result.code == "01") {
                response.send({ code: "01", msg: "ok", data: bookinfo.bid });
            } else {
                response.send({ code: "04", msg: "error", data: null });
            }
        })
    });
})












/*---get default---*/
app.get("*", (request, response) => {
    // response.redirect("./404.html");
    response.send({ code: "404" });
});

/*---pc 后端---*/

app.post('/admininfo',(request,response)=>{
    const {username,password} = request.body
    management(username,res=>{
       
        response.send({code:'01',msg:"ok",data:res.data})
       
    })
    
})